<template>
  <div class="knowledge-editor">
    <!-- 编辑器头部 -->
    <div class="editor-header">
      <div class="header-left">
        <Button
          type="secondary"
          variant="text"
          icon="arrow-left"
          @click="$emit('back')"
        >
          返回
        </Button>

        <div class="editor-title">
          <h3 class="title-text">
            {{ isEditing ? "编辑知识库" : "新建知识库" }}
          </h3>
          <span v-if="knowledgeBase?.name" class="subtitle-text">
            {{ knowledgeBase.name }}
          </span>
        </div>
      </div>

      <div class="header-actions">
        <Button
          type="secondary"
          icon="eye"
          @click="togglePreview"
          :class="{ active: showPreview }"
        >
          预览
        </Button>

        <Button
          type="secondary"
          icon="save"
          @click="saveDraft"
          :loading="saving"
        >
          保存草稿
        </Button>

        <Button
          type="primary"
          icon="check"
          @click="saveKnowledgeBase"
          :loading="saving"
        >
          {{ isEditing ? "更新" : "创建" }}
        </Button>
      </div>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-body">
      <!-- 左侧编辑区 -->
      <div class="editor-main" :class="{ 'with-preview': showPreview }">
        <!-- 基本信息 -->
        <div class="basic-info-section">
          <h4 class="section-title">
            <Icon name="info" :size="16" />
            基本信息
          </h4>

          <div class="form-grid">
            <div class="form-group">
              <label class="form-label">知识库名称 *</label>
              <Input
                v-model="formData.name"
                placeholder="请输入知识库名称"
                :error="errors.name"
                @blur="validateField('name')"
              />
            </div>

            <div class="form-group">
              <label class="form-label">分类</label>
              <select v-model="formData.category" class="form-select">
                <option value="general">通用</option>
                <option value="technical">技术</option>
                <option value="business">商业</option>
                <option value="personal">个人</option>
                <option value="academic">学术</option>
              </select>
            </div>

            <div class="form-group full-width">
              <label class="form-label">描述</label>
              <textarea
                v-model="formData.description"
                placeholder="请输入知识库描述"
                class="form-textarea"
                rows="3"
              ></textarea>
            </div>

            <div class="form-group">
              <label class="form-label">标签</label>
              <div class="tags-input">
                <div class="tags-list">
                  <span
                    v-for="(tag, index) in formData.tags"
                    :key="index"
                    class="tag-item"
                  >
                    {{ tag }}
                    <Button
                      type="secondary"
                      variant="text"
                      icon="x"
                      size="small"
                      @click="removeTag(index)"
                    />
                  </span>
                </div>

                <Input
                  v-model="newTag"
                  placeholder="输入标签后按回车"
                  size="small"
                  @keyup.enter="addTag"
                  class="tag-input"
                />
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">访问权限</label>
              <select v-model="formData.access" class="form-select">
                <option value="private">私有</option>
                <option value="shared">共享</option>
                <option value="public">公开</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 文档管理 -->
        <div class="documents-section">
          <div class="section-header">
            <h4 class="section-title">
              <Icon name="file-text" :size="16" />
              文档管理
              <span class="document-count">({{ documents.length }})</span>
            </h4>

            <div class="section-actions">
              <Button type="secondary" icon="upload" @click="uploadDocuments">
                上传文档
              </Button>

              <Button type="secondary" icon="plus" @click="createDocument">
                新建文档
              </Button>
            </div>
          </div>

          <!-- 文档列表 -->
          <div class="documents-list">
            <div
              v-for="doc in documents"
              :key="doc.id"
              class="document-item"
              :class="{ active: selectedDocument?.id === doc.id }"
              @click="selectDocument(doc)"
            >
              <div class="doc-icon">
                <Icon :name="getDocumentIcon(doc.type)" :size="16" />
              </div>

              <div class="doc-info">
                <div class="doc-name">{{ doc.name }}</div>
                <div class="doc-meta">
                  <span class="doc-size">{{ formatSize(doc.size) }}</span>
                  <span class="doc-time">{{ formatTime(doc.updatedAt) }}</span>
                </div>
              </div>

              <div class="doc-status">
                <span
                  class="status-indicator"
                  :class="`status-${doc.status}`"
                  :title="getStatusText(doc.status)"
                ></span>
              </div>

              <div class="doc-actions">
                <Button
                  type="secondary"
                  variant="text"
                  icon="edit"
                  size="small"
                  @click.stop="editDocument(doc)"
                  title="编辑"
                />

                <Button
                  type="danger"
                  variant="text"
                  icon="trash"
                  size="small"
                  @click.stop="deleteDocument(doc)"
                  title="删除"
                />
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="documents.length === 0" class="empty-documents">
              <Icon name="file-text" :size="48" class="empty-icon" />
              <p class="empty-text">暂无文档</p>
              <Button type="primary" icon="plus" @click="createDocument">
                添加第一个文档
              </Button>
            </div>
          </div>
        </div>

        <!-- 文档编辑器 -->
        <div v-if="selectedDocument" class="document-editor-section">
          <div class="section-header">
            <h4 class="section-title">
              <Icon name="edit" :size="16" />
              编辑文档: {{ selectedDocument.name }}
            </h4>

            <div class="section-actions">
              <Button
                type="secondary"
                variant="text"
                icon="x"
                @click="closeDocumentEditor"
              >
                关闭
              </Button>
            </div>
          </div>

          <div class="document-editor">
            <div class="editor-toolbar">
              <div class="toolbar-group">
                <Button
                  type="secondary"
                  variant="text"
                  icon="bold"
                  size="small"
                  @click="formatText('bold')"
                  title="粗体"
                />

                <Button
                  type="secondary"
                  variant="text"
                  icon="italic"
                  size="small"
                  @click="formatText('italic')"
                  title="斜体"
                />

                <Button
                  type="secondary"
                  variant="text"
                  icon="underline"
                  size="small"
                  @click="formatText('underline')"
                  title="下划线"
                />
              </div>

              <div class="toolbar-group">
                <Button
                  type="secondary"
                  variant="text"
                  icon="list"
                  size="small"
                  @click="formatText('ul')"
                  title="无序列表"
                />

                <Button
                  type="secondary"
                  variant="text"
                  icon="list-ordered"
                  size="small"
                  @click="formatText('ol')"
                  title="有序列表"
                />

                <Button
                  type="secondary"
                  variant="text"
                  icon="link"
                  size="small"
                  @click="insertLink"
                  title="插入链接"
                />
              </div>

              <div class="toolbar-group">
                <Button
                  type="secondary"
                  variant="text"
                  icon="image"
                  size="small"
                  @click="insertImage"
                  title="插入图片"
                />

                <Button
                  type="secondary"
                  variant="text"
                  icon="code"
                  size="small"
                  @click="insertCode"
                  title="插入代码"
                />
              </div>
            </div>

            <textarea
              v-model="selectedDocument.content"
              class="document-textarea"
              placeholder="在此输入文档内容..."
              @input="onDocumentContentChange"
            ></textarea>
          </div>
        </div>

        <!-- 高级设置 -->
        <div class="advanced-settings-section">
          <div class="section-header">
            <h4 class="section-title">
              <Icon name="settings" :size="16" />
              高级设置
            </h4>

            <Button
              type="secondary"
              variant="text"
              icon="chevron-down"
              @click="toggleAdvancedSettings"
              :class="{ active: showAdvancedSettings }"
            />
          </div>

          <div v-if="showAdvancedSettings" class="advanced-settings">
            <div class="settings-grid">
              <div class="setting-group">
                <label class="setting-label">
                  <input
                    v-model="formData.settings.enableSearch"
                    type="checkbox"
                    class="setting-checkbox"
                  />
                  启用全文搜索
                </label>
                <p class="setting-description">允许在知识库中进行全文搜索</p>
              </div>

              <div class="setting-group">
                <label class="setting-label">
                  <input
                    v-model="formData.settings.enableVersioning"
                    type="checkbox"
                    class="setting-checkbox"
                  />
                  启用版本控制
                </label>
                <p class="setting-description">保存文档的历史版本</p>
              </div>

              <div class="setting-group">
                <label class="setting-label">
                  <input
                    v-model="formData.settings.enableCollaboration"
                    type="checkbox"
                    class="setting-checkbox"
                  />
                  启用协作编辑
                </label>
                <p class="setting-description">允许多人同时编辑文档</p>
              </div>

              <div class="setting-group">
                <label class="setting-label">
                  <input
                    v-model="formData.settings.autoSave"
                    type="checkbox"
                    class="setting-checkbox"
                  />
                  自动保存
                </label>
                <p class="setting-description">定期自动保存更改</p>
              </div>
            </div>

            <div class="setting-group">
              <label class="form-label">自动保存间隔（秒）</label>
              <Input
                v-model.number="formData.settings.autoSaveInterval"
                type="number"
                min="10"
                max="300"
                :disabled="!formData.settings.autoSave"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧预览区 -->
      <div v-if="showPreview" class="editor-preview">
        <div class="preview-header">
          <h4 class="preview-title">
            <Icon name="eye" :size="16" />
            预览
          </h4>

          <Button
            type="secondary"
            variant="text"
            icon="x"
            @click="togglePreview"
          />
        </div>

        <div class="preview-content">
          <!-- 知识库信息预览 -->
          <div class="preview-section">
            <h5 class="preview-section-title">基本信息</h5>
            <div class="preview-info">
              <div class="info-item">
                <span class="info-label">名称:</span>
                <span class="info-value">{{ formData.name || "未命名" }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分类:</span>
                <span class="info-value">{{
                  getCategoryText(formData.category)
                }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">描述:</span>
                <span class="info-value">{{
                  formData.description || "暂无描述"
                }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">标签:</span>
                <div class="preview-tags">
                  <span
                    v-for="tag in formData.tags"
                    :key="tag"
                    class="preview-tag"
                  >
                    {{ tag }}
                  </span>
                  <span v-if="formData.tags.length === 0" class="info-value">
                    暂无标签
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 文档预览 -->
          <div class="preview-section">
            <h5 class="preview-section-title">
              文档列表 ({{ documents.length }})
            </h5>
            <div class="preview-documents">
              <div
                v-for="doc in documents"
                :key="doc.id"
                class="preview-document"
              >
                <Icon :name="getDocumentIcon(doc.type)" :size="14" />
                <span class="doc-name">{{ doc.name }}</span>
                <span class="doc-size">{{ formatSize(doc.size) }}</span>
              </div>

              <div v-if="documents.length === 0" class="empty-preview">
                暂无文档
              </div>
            </div>
          </div>

          <!-- 当前文档内容预览 -->
          <div v-if="selectedDocument" class="preview-section">
            <h5 class="preview-section-title">
              {{ selectedDocument.name }} 内容预览
            </h5>
            <div class="preview-document-content">
              <div
                class="rendered-content"
                v-html="renderMarkdown(selectedDocument.content)"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传对话框 -->
    <input
      ref="fileInput"
      type="file"
      multiple
      accept=".txt,.md,.pdf,.doc,.docx"
      style="display: none"
      @change="handleFileUpload"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useKnowledgeStore } from "@/stores/knowledge";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Input from "@/components/common/Input.vue";

interface Document {
  id: string;
  name: string;
  type: string;
  content: string;
  size: number;
  status: "draft" | "published" | "processing" | "error";
  createdAt: number;
  updatedAt: number;
}

interface KnowledgeBase {
  id?: string;
  name: string;
  description?: string;
  category: string;
  tags: string[];
  access: "private" | "shared" | "public";
  settings: {
    enableSearch: boolean;
    enableVersioning: boolean;
    enableCollaboration: boolean;
    autoSave: boolean;
    autoSaveInterval: number;
  };
  documents?: Document[];
  createdAt?: number;
  updatedAt?: number;
}

interface Props {
  knowledgeBase?: KnowledgeBase;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  back: [];
  save: [kb: KnowledgeBase];
  update: [kb: KnowledgeBase];
}>();

// Store
const knowledgeStore = useKnowledgeStore();

// 响应式数据
const saving = ref(false);
const showPreview = ref(false);
const showAdvancedSettings = ref(false);
const selectedDocument = ref<Document | null>(null);
const newTag = ref("");
const fileInput = ref<HTMLInputElement>();

// 表单数据
const formData = ref<KnowledgeBase>({
  name: "",
  description: "",
  category: "general",
  tags: [],
  access: "private",
  settings: {
    enableSearch: true,
    enableVersioning: false,
    enableCollaboration: false,
    autoSave: true,
    autoSaveInterval: 30,
  },
});

// 文档列表
const documents = ref<Document[]>([]);

// 表单验证
const errors = ref<Record<string, string>>({});

// 计算属性
const isEditing = computed(() => !!props.knowledgeBase?.id);

// 方法
const validateField = (field: string) => {
  switch (field) {
    case "name":
      if (!formData.value.name.trim()) {
        errors.value.name = "请输入知识库名称";
      } else {
        delete errors.value.name;
      }
      break;
  }
};

const validateForm = (): boolean => {
  validateField("name");
  return Object.keys(errors.value).length === 0;
};

// 标签管理
const addTag = () => {
  const tag = newTag.value.trim();
  if (tag && !formData.value.tags.includes(tag)) {
    formData.value.tags.push(tag);
    newTag.value = "";
  }
};

const removeTag = (index: number) => {
  formData.value.tags.splice(index, 1);
};

// 文档管理
const createDocument = () => {
  const newDoc: Document = {
    id: `doc_${Date.now()}`,
    name: `新文档 ${documents.value.length + 1}`,
    type: "text",
    content: "",
    size: 0,
    status: "draft",
    createdAt: Date.now(),
    updatedAt: Date.now(),
  };

  documents.value.push(newDoc);
  selectedDocument.value = newDoc;
};

const selectDocument = (doc: Document) => {
  selectedDocument.value = doc;
};

const editDocument = (doc: Document) => {
  selectedDocument.value = doc;
};

const deleteDocument = (doc: Document) => {
  if (confirm(`确定要删除文档 "${doc.name}" 吗？`)) {
    const index = documents.value.findIndex((d) => d.id === doc.id);
    if (index > -1) {
      documents.value.splice(index, 1);
      if (selectedDocument.value?.id === doc.id) {
        selectedDocument.value = null;
      }
    }
  }
};

const closeDocumentEditor = () => {
  selectedDocument.value = null;
};

const uploadDocuments = () => {
  fileInput.value?.click();
};

const handleFileUpload = (event: Event) => {
  const files = (event.target as HTMLInputElement).files;
  if (!files) return;

  Array.from(files).forEach((file) => {
    const doc: Document = {
      id: `doc_${Date.now()}_${Math.random()}`,
      name: file.name,
      type: getFileType(file.name),
      content: "",
      size: file.size,
      status: "processing",
      createdAt: Date.now(),
      updatedAt: Date.now(),
    };

    documents.value.push(doc);

    // 读取文件内容
    const reader = new FileReader();
    reader.onload = (e) => {
      doc.content = e.target?.result as string;
      doc.status = "draft";
    };
    reader.readAsText(file);
  });
};

// 文档编辑
const onDocumentContentChange = () => {
  if (selectedDocument.value) {
    selectedDocument.value.updatedAt = Date.now();
    selectedDocument.value.size = new Blob([
      selectedDocument.value.content,
    ]).size;
  }
};

const formatText = (format: string) => {
  // 文本格式化逻辑
  console.log("格式化文本:", format);
};

const insertLink = () => {
  const url = prompt("请输入链接地址:");
  if (url && selectedDocument.value) {
    const text = prompt("请输入链接文本:", url);
    const markdown = `[${text || url}](${url})`;
    selectedDocument.value.content += markdown;
  }
};

const insertImage = () => {
  const url = prompt("请输入图片地址:");
  if (url && selectedDocument.value) {
    const alt = prompt("请输入图片描述:", "图片");
    const markdown = `![${alt}](${url})`;
    selectedDocument.value.content += markdown;
  }
};

const insertCode = () => {
  if (selectedDocument.value) {
    const code = "```\n// 在此输入代码\n```";
    selectedDocument.value.content += code;
  }
};

// 预览相关
const togglePreview = () => {
  showPreview.value = !showPreview.value;
};

const toggleAdvancedSettings = () => {
  showAdvancedSettings.value = !showAdvancedSettings.value;
};

const renderMarkdown = (content: string): string => {
  // 简单的 Markdown 渲染
  return content
    .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
    .replace(/\*(.*?)\*/g, "<em>$1</em>")
    .replace(/`(.*?)`/g, "<code>$1</code>")
    .replace(/\n/g, "<br>");
};

// 保存操作
const saveDraft = async () => {
  if (!validateForm()) return;

  saving.value = true;
  try {
    const kbData = {
      ...formData.value,
      documents: documents.value,
      updatedAt: Date.now(),
    };

    await knowledgeStore.saveDraft(kbData);
    console.log("草稿保存成功");
  } catch (error) {
    console.error("保存草稿失败:", error);
  } finally {
    saving.value = false;
  }
};

const saveKnowledgeBase = async () => {
  if (!validateForm()) return;

  saving.value = true;
  try {
    const kbData = {
      ...formData.value,
      documents: documents.value,
      updatedAt: Date.now(),
    };

    if (isEditing.value) {
      await knowledgeStore.updateKnowledgeBase(
        props.knowledgeBase!.id!,
        kbData,
      );
      emit("update", kbData);
    } else {
      const newKb = await knowledgeStore.createKnowledgeBase(kbData);
      emit("save", newKb);
    }
  } catch (error) {
    console.error("保存知识库失败:", error);
  } finally {
    saving.value = false;
  }
};

// 工具函数
const getFileType = (filename: string): string => {
  const ext = filename.split(".").pop()?.toLowerCase();
  const typeMap: Record<string, string> = {
    txt: "text",
    md: "markdown",
    pdf: "pdf",
    doc: "document",
    docx: "document",
  };
  return typeMap[ext || ""] || "unknown";
};

const getDocumentIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    text: "file-text",
    markdown: "file-text",
    pdf: "file",
    document: "file",
    unknown: "file",
  };
  return iconMap[type] || "file";
};

const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    draft: "草稿",
    published: "已发布",
    processing: "处理中",
    error: "错误",
  };
  return statusMap[status] || status;
};

const getCategoryText = (category: string): string => {
  const categoryMap: Record<string, string> = {
    general: "通用",
    technical: "技术",
    business: "商业",
    personal: "个人",
    academic: "学术",
  };
  return categoryMap[category] || category;
};

const formatSize = (bytes: number): string => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp);
  return date.toLocaleString("zh-CN");
};

// 初始化
const initializeForm = () => {
  if (props.knowledgeBase) {
    formData.value = { ...props.knowledgeBase };
    documents.value = props.knowledgeBase.documents || [];
  }
};

// 监听器
watch(() => props.knowledgeBase, initializeForm, { immediate: true });

// 生命周期
onMounted(() => {
  initializeForm();
});
</script>

<style scoped>
/* 知识库编辑器基础样式 */
.knowledge-editor {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--bg-primary);
  overflow: hidden;
}

/* 编辑器头部 */
.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.editor-title {
  display: flex;
  flex-direction: column;
}

.title-text {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.subtitle-text {
  font-size: 14px;
  color: var(--text-secondary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 编辑器主体 */
.editor-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.editor-main {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  transition: all 0.3s ease;
}

.editor-main.with-preview {
  flex: 0 0 60%;
}

/* 表单样式 */
.basic-info-section,
.documents-section,
.document-editor-section,
.advanced-settings-section {
  margin-bottom: 32px;
  background-color: var(--bg-secondary);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border-color);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.document-count {
  font-size: 12px;
  color: var(--text-tertiary);
  font-weight: normal;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.form-select,
.form-textarea {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

/* 标签输入 */
.tags-input {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background-color: var(--primary-color-light);
  color: var(--primary-color);
  border-radius: 4px;
  font-size: 12px;
}

.tag-input {
  max-width: 200px;
}

/* 文档列表 */
.documents-list {
  max-height: 300px;
  overflow-y: auto;
}

.document-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.document-item:hover {
  background-color: var(--bg-tertiary);
}

.document-item.active {
  border-color: var(--primary-color);
  background-color: var(--primary-color-light);
}

.doc-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
}

.doc-info {
  flex: 1;
}

.doc-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 2px;
}

.doc-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--text-tertiary);
}

.doc-status {
  display: flex;
  align-items: center;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-draft {
  background-color: var(--warning-color);
}

.status-published {
  background-color: var(--success-color);
}

.status-processing {
  background-color: var(--info-color);
}

.status-error {
  background-color: var(--error-color);
}

.doc-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.document-item:hover .doc-actions {
  opacity: 1;
}

/* 空状态 */
.empty-documents {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  color: var(--text-tertiary);
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0 0 16px;
}

/* 文档编辑器 */
.document-editor {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.editor-toolbar {
  display: flex;
  gap: 8px;
  padding: 8px 12px;
  background-color: var(--bg-tertiary);
  border-bottom: 1px solid var(--border-color);
}

.toolbar-group {
  display: flex;
  gap: 4px;
}

.toolbar-group:not(:last-child) {
  border-right: 1px solid var(--border-color);
  padding-right: 8px;
  margin-right: 8px;
}

.document-textarea {
  width: 100%;
  min-height: 300px;
  padding: 16px;
  border: none;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  line-height: 1.5;
  resize: vertical;
}

.document-textarea:focus {
  outline: none;
}

/* 高级设置 */
.advanced-settings {
  margin-top: 16px;
}

.settings-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.setting-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.setting-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  cursor: pointer;
}

.setting-checkbox {
  width: 16px;
  height: 16px;
}

.setting-description {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0;
  margin-left: 24px;
}

/* 预览区域 */
.editor-preview {
  flex: 0 0 40%;
  border-left: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.preview-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.preview-section {
  margin-bottom: 24px;
}

.preview-section-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid var(--border-color);
}

.preview-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-label {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 60px;
  font-weight: 500;
}

.info-value {
  font-size: 12px;
  color: var(--text-primary);
  flex: 1;
}

.preview-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.preview-tag {
  padding: 2px 6px;
  background-color: var(--primary-color-light);
  color: var(--primary-color);
  border-radius: 4px;
  font-size: 10px;
}

.preview-documents {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.preview-document {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  background-color: var(--bg-primary);
  border-radius: 4px;
  font-size: 12px;
}

.empty-preview {
  font-size: 12px;
  color: var(--text-tertiary);
  text-align: center;
  padding: 20px;
}

.preview-document-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 12px;
  background-color: var(--bg-primary);
  border-radius: 6px;
  border: 1px solid var(--border-color);
}

.rendered-content {
  font-size: 12px;
  line-height: 1.5;
  color: var(--text-primary);
}

/* 响应式 */
@media (max-width: 1024px) {
  .editor-main.with-preview {
    flex: 0 0 50%;
  }

  .editor-preview {
    flex: 0 0 50%;
  }
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-end;
  }

  .editor-body {
    flex-direction: column;
  }

  .editor-main {
    flex: 1;
    padding: 16px;
  }

  .editor-main.with-preview {
    flex: 0 0 60%;
  }

  .editor-preview {
    flex: 0 0 40%;
    border-left: none;
    border-top: 1px solid var(--border-color);
  }

  .form-grid,
  .settings-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .editor-header,
  .preview-header {
    padding: 12px 16px;
  }

  .editor-main,
  .preview-content {
    padding: 12px;
  }

  .basic-info-section,
  .documents-section,
  .document-editor-section,
  .advanced-settings-section {
    padding: 16px;
  }
}

/* 滚动条样式 */
.editor-main::-webkit-scrollbar,
.preview-content::-webkit-scrollbar,
.documents-list::-webkit-scrollbar {
  width: 6px;
}

.editor-main::-webkit-scrollbar-track,
.preview-content::-webkit-scrollbar-track,
.documents-list::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 3px;
}

.editor-main::-webkit-scrollbar-thumb,
.preview-content::-webkit-scrollbar-thumb,
.documents-list::-webkit-scrollbar-thumb {
  background: var(--text-tertiary);
  border-radius: 3px;
}

.editor-main::-webkit-scrollbar-thumb:hover,
.preview-content::-webkit-scrollbar-thumb:hover,
.documents-list::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}
</style>
